import os.path
import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

import click
from operator import itemgetter

from dp_analysis.analysis.base import DrawBase
from dp_analysis.db.connection import Mysql
from dp_analysis.utils.decorate import decorate


class DrawShop(DrawBase):
    """
    绘制店铺相关的图
    """

    def __init__(self):
        super().__init__()

        self.save_path = "shop/"
        self.top5_save_path = "shop/top5/"

    @decorate(obj_name="DrawShop")
    def analyse(self, db, shop_count, top5):
        if shop_count:
            self.draw_shop_count(db)

        if top5:
            self.draw_top5(db)
    
    def draw_shop_count(self, db):
        with Mysql("dp", db) as mysql:
            connection = mysql.engine.connect()

            attr, value = list(), list()
            for (region, _count) in connection.execute(
                    "SELECT region, COUNT(*) FROM shop_info GROUP BY (region);").fetchall():
                attr.append(region)
                value.append(_count)

        self.draw_pie("12大热门地区店铺数量占比", attr, value, self.save_path, "各地区店铺数量占比.html")

    def draw_top5(self, db):
        with Mysql("dp", db) as mysql:
            connection = mysql.engine.connect()

            region_list = [region for (region, ) in connection.execute(
                "SELECT region FROM regional_table_of_delicacies;").fetchall()]
            for region in region_list:
                print(f"开始加载{region}地区数据...")
                result_dict = dict()
                for district, average_price in connection.execute(
                        f"SELECT district, average_price FROM shop_info "
                        f"WHERE region={region!r} AND district !=''").fetchall():
                    result_dict.setdefault(district, dict())
                    result_dict[district].setdefault("number", 0)
                    result_dict[district].setdefault("price", 0.0)
                    result_dict[district]["number"] += 1
                    result_dict[district]["price"] += float(average_price)

                result_list = list()
                for district, info_dict in result_dict.items():
                    number = info_dict.get("number")
                    price = info_dict.get("price")

                    result_list.append([district, number, float("%.2f" % (price / number))])
                result_list.sort(key=itemgetter(1, 2), reverse=True)

                attr, count_list, price_list = list(), list(), list()
                for (x, y, z) in result_list[:5]:
                    attr.append(x)
                    count_list.append(y)
                    price_list.append(z)
                print(f"{region}地区数据加载完成！")
                self.draw_top5_bar(attr, count_list, price_list, self.top5_save_path, region)


@click.command()
@click.option("--db", default=0, help="请选择使用的数据库")
@click.option("-sc", "--shop_count", prompt="是否绘制店铺数量[0 or 1]", help="是否绘制店铺数量；1：绘制、0：不绘制")
@click.option("-top", "--top5", prompt="是否绘制消费水平[0 or 1]",
              help="是否绘制各地区餐厅分布最多的5个地区及消费水平；1：绘制、0：不绘制")
def main(db, shop_count, top5):
    draw_shop = DrawShop()
    draw_shop.analyse(db, int(shop_count), int(top5))


if __name__ == '__main__':
    main()
